//
//  Mappable+Extension.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import ObjectMapper

public extension Mappable {

    //MARK: -- 模型转字典
    func reflectToDict() -> [String:Any] {
        /// 循环 递归
        ///
        /// -Parameters:
        ///  - m: 镜像
        ///  - isArray: value 的值是否是数组
        /// -Returns: 子集 字典
        func forDicFuntion(m: Mirror, isArray: Bool = false) -> [String: Any] {
            var dictTemp = [String:Any]()
            for case let(key?, value)in m.children{
                let n = Mirror(reflecting: value)
                if(n.displayStyle == .collection) {
                    var array = [[String:Any]]()
                    for index in n.children{
                        let x = Mirror(reflecting: index)
                        array.append(forDicFuntion(m: x,isArray:true))
                    }
                    dictTemp[key] = array
                } else if (n.displayStyle == .set || n.displayStyle == .optional) {
                    continue
                } else {
                    if(n.children.count > 0) {
                        if(isArray){
                            dictTemp = forDicFuntion(m: n)
                        }else{
                            dictTemp[key] = forDicFuntion(m: n)
                        }
                    } else {
                        dictTemp[key] = value
                    }
                }
            }
            return dictTemp
        }

        let mirro = Mirror(reflecting: self)
        return forDicFuntion(m: mirro)
    }
}
